package com.kindac.together.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import com.kindac.together.R;
import com.kindac.together.common.Kin;
import com.kindac.together.uitl.Utils;

/** 现在只为显示消息图标 */
public class HeadService extends Service {

    /** 启动service用到 */
    @SuppressWarnings("rawtypes")
    private static final Class[] mStartSignature      = new Class[] { int.class, Notification.class };
    @SuppressWarnings("rawtypes")
    private static final Class[] mStopSignature       = new Class[] { boolean.class };
    private NotificationManager  mNM;
    private Method               mStartForeground;
    private Method               mStopForeground;
    private Object[]             mStartForegroundArgs = new Object[2];
    private Object[]             mStopForegroundArgs  = new Object[1];

    // 音乐文件
    private MediaPlayer          mediaPlayer;

    public void onCreate() {

        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Log.e(HeadService.class.getSimpleName(), "## service Create");
        try {
            mStartForeground = getClass().getMethod("startForeground", mStartSignature);
            mStopForeground = getClass().getMethod("stopForeground", mStopSignature);
        } catch (NoSuchMethodException e) {
            // Running on an older platform.
            Log.w(HeadService.class.getSimpleName(), "## service unCreate" + e);
            mStartForeground = mStopForeground = null;
        }
    }

    private void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.
        if (mStartForeground != null) {

            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w(HeadService.class.getSimpleName(), "## Unable to invoke startForeground" + e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w(HeadService.class.getSimpleName(), "## Unable to invoke startForeground" + e);
            }
            return;
        }
        // Fall back on the old API.
        setForeground(true);
        mNM.notify(id, notification);
    }

    /**
     * This is a wrapper around the new stopForeground method, using the older APIs if it is not available.
     */
    private void stopForegroundCompat(int id) {
        // If we have the new stopForeground API, then use it.
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w(HeadService.class.getSimpleName(), "## Unable to invoke stopForeground" + e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w(HeadService.class.getSimpleName(), "## Unable to invoke stopForeground" + e);
            }
            return;
        }
        // Fall back on the old API. Note to cancel BEFORE changing the
        // foreground state, since we could be killed at that point.
        mNM.cancel(id);
        setForeground(false);
    }

    @Override
    public void onDestroy() {
        // Make sure our notification is gone.

        if (mediaPlayer != null) mediaPlayer.stop();

        stopForegroundCompat(R.string.app_name);

    }

    // This is the old onStart method that will be called on the pre-2.0
    // platform. On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(HeadService.class.getSimpleName(), "## server start");
        handleCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    public IBinder onBind(Intent intent) {
        /*
         * 调用者和Service间是依靠IBinder对象进行通信的，Service的onBind()返回的IBinder对象传递给调用者中
         * ServiceConnection对象的onServiceConnected()方法（以参数形式接收）；
         * TService的调用者就可以利用这个IBinder获得TService对象，进而对TService进行操作控制；
         * TService的调用者也可以利用这个IBinder获得其他信息，比如TService的状态statusCode。
         */
        return null;
    }

    public boolean onUnbind(Intent i) {
        return false;
    }

    private void handleCommand(Intent intent) {

        if (intent == null) return;

        if (Kin.isMusic && Kin.PAUSE.equals(intent.getAction())) {
            pauseMusic();
        } else if (Kin.isMusic && Kin.MUSIC.equals(intent.getAction())) {
            startMusic();
        } else {

        }
        // In this sample, we'll use the same text for the ticker and the
        // expanded notification
        // CharSequence text = intent.getStringExtra("message");

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(intent.getIntExtra("icon", R.drawable.t_icon), null,
                                                     System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this
        // notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Kin.curAct.getClass()), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.info), null, contentIntent);

        startForegroundCompat(R.string.app_name, notification);
    }

    private void startMusic() {

        if (mediaPlayer == null) {
            try {

                // 设置音量
                AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);

                int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

                int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);

                Log.i(HeadService.class.getName(), "max : " + max + " current : " + current);

                am.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (max * 3 / 5), 0);
                // 随机选择歌曲
                int music = Utils.getRandom(Kin.arrMusic.length);

                // R.raw.mmp是资源文件，MP3格式的
                mediaPlayer = MediaPlayer.create(this, Kin.arrMusic[music]);
                mediaPlayer.setLooping(true);
                mediaPlayer.start();
            } catch (Exception e) {
            }
        } else {
            mediaPlayer.start();
        }
    }

    private void pauseMusic() {
        if (mediaPlayer != null) mediaPlayer.pause();
    }
}
